import axios from 'axios'
import { ElMessage } from 'element-plus';
import { refreshToken } from '../api/user'
import NproGress from 'nprogress';
import 'nprogress/nprogress.css'


const instance = axios.create({
    baseURL: '/api',
    timeout: 30000
});

// 请求拦截器
instance.interceptors.request.use((config) => {
    // token添加到请求头
    config.headers.Authorization = localStorage.getItem('token') ? localStorage.getItem('token') : '';
    // 开启顶部进度条
    NproGress.start()
    return config;
}, (error) => {
    return Promise.reject(error);
});

// 响应拦截器
instance.interceptors.response.use((data) => {
    // 关闭进度条
    NproGress.done()
    switch (data.data.code) {
        case 0:
            ElMessage.success(data.data.message)
            break;
        case 1:
            ElMessage.warning(data.data.message)
            break;
    }
    return data;
},
    async (error) => {
        // console.log(error)
        const code = error.response.status
        if (code === 401) {
            // 如果当前状态为401，重新获取一次token
            await refreshToken({
                refreshToken: localStorage.getItem('refreshToken')
            }).then(res => {
                localStorage.setItem('token', res.data.token)
                localStorage.setItem('refreshToken', res.data.refreshToken)
            })
            return instance(error.config)
        }
        return Promise.reject(error);
    })

export default instance;